package com.qqtech.oss.aliyun;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.qqtech.admin.context.BaseFileController;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.Result;

@Controller
@RequestMapping(value = "/oss")
public class UploadController extends BaseFileController {
	private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);

	@Resource
	private FileClient ossFileClient;

	/**
	 * 上传图片，并返回图片路径
	 * 
	 * @param request
	 * @return 图片路径Result.get("path")，如"/user/aaa.jpg"
	 * @throws BizzException
	 * @throws IOException
	 */
	@RequestMapping(value = "/app/upload")
	@ResponseBody
	public Result upload(HttpServletRequest request) throws BizzException, IOException {
		Result result = new Result();
		MultipartHttpServletRequest dmhRequest = (DefaultMultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = dmhRequest.getFileMap();
		if (fileMap == null || fileMap.isEmpty() || fileMap.size() == 0) {
			throw new BizzException("没有需要上传的文件");
		}
		StringBuffer sbPath = new StringBuffer();
		for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			UploadResult ur = upload(entry.getValue(), entry.getKey());
			if (ur.isUploadOk()) {
				sbPath.append(ur.getFilePath()).append(";");
			}
		}
		String path = sbPath.toString();
		path = StringUtil.removeEndWiths(path, ";");
		result.put("path", path);
		return result;
	}

	/**
	 * 上传图片，并返回图片路径，多路径已以分号拼接好
	 * 
	 * @param request
	 * @return 图片路径Result.get("path")，如"/user/aaa.jpg;/user/bbb.png"
	 * @throws BizzException
	 * @throws IOException
	 */
	@RequestMapping(value = "/app/form")
	@ResponseBody
	public Result form(HttpServletRequest request) throws BizzException, IOException {
		Result result = new Result();
		MultipartHttpServletRequest dmhRequest = (DefaultMultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = dmhRequest.getFileMap();
		if (fileMap == null || fileMap.isEmpty() || fileMap.size() == 0) {
			throw new BizzException("没有需要上传的文件");
		}
		String folder = "";
		Map<String, String[]> parameterMap = dmhRequest.getParameterMap();
		if (parameterMap != null && !parameterMap.isEmpty() && parameterMap.size() > 0) {
			for (Entry<String, String[]> entry : parameterMap.entrySet()) {
				String[] paramArr = entry.getValue();
				if (paramArr != null && paramArr.length > 0) {
					if ("folder".endsWith(entry.getKey())) {
						folder = paramArr[0];
						break;
					}
				}
			}
		}
		StringBuffer sbPath = new StringBuffer();
		for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			UploadResult ur = upload(entry.getValue(), folder);
			if (ur.isUploadOk()) {
				sbPath.append(ur.getFilePath()).append(";");
			}
		}
		String path = sbPath.toString();
		path = StringUtil.removeEndWiths(path, ";");
		result.put("path", path);
		return result;
	}

	@RequestMapping(value = "/app/upload2", method = RequestMethod.POST)
	@ResponseBody
	public Result upload(@RequestParam String folder,
			@RequestParam(value = "uploadkey1", required = false) MultipartFile uploadFile1,
			@RequestParam(value = "uploadkey2", required = false) MultipartFile uploadFile2,
			@RequestParam(value = "uploadkey3", required = false) MultipartFile uploadFile3,
			@RequestParam(value = "uploadkey4", required = false) MultipartFile uploadFile4,
			@RequestParam(value = "uploadkey5", required = false) MultipartFile uploadFile5,
			@RequestParam(value = "uploadkey6", required = false) MultipartFile uploadFile6,
			@RequestParam(value = "uploadkey7", required = false) MultipartFile uploadFile7,
			@RequestParam(value = "uploadkey8", required = false) MultipartFile uploadFile8,
			@RequestParam(value = "uploadkey9", required = false) MultipartFile uploadFile9,
			@RequestParam(value = "uploadkey10", required = false) MultipartFile uploadFile10) throws BizzException {
		Result retDomain = new Result();
		MultipartFile[] uploadFiles = { uploadFile1, uploadFile2, uploadFile3, uploadFile4, uploadFile5, uploadFile6,
				uploadFile7, uploadFile8, uploadFile9, uploadFile10 };
		Object[] parmams = { folder, uploadFiles };
		LOG.info("fileType={},uploadFiles={}", parmams);
		try {
			if (folder == null) {
				folder = "OTHER";
			}
			List<UploadResult> uploadResults = new ArrayList<UploadResult>();
			for (MultipartFile file : uploadFiles) {
				if (file != null && !file.isEmpty()) {
					UploadResult uploadResult = upload(file, folder);
					uploadResults.add(uploadResult);
				}
			}
			if (uploadResults.size() > 0) {
				retDomain.put("uploadResults", uploadResults);
			} else {
				retDomain.addErr("请选择要上传的文件");
			}
		} catch (Exception e1) {
			LOG.error("文件上传异常{},e={},{}", e1, e1.getStackTrace());
			e1.printStackTrace();
			throw new BizzException("文件上传异常");
		}
		return retDomain;
	}

	private UploadResult upload(MultipartFile uploadFile, String folder) throws IOException {
		String originalFilename = uploadFile.getOriginalFilename();
		originalFilename = StringUtil.removeEndWiths(originalFilename, ".do");
		String filename = ossFileClient.buildStorePath(folder, originalFilename);
		UploadResult uploadResult = ossFileClient.putObject(filename, uploadFile.getInputStream(), uploadFile.getSize());
		LOG.info("返回参数: uploadResult={}", uploadResult);
		return uploadResult;
	}
}
